package com.ydkj.a37e_mall.Classes.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.LoginActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.OrderDetail;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ProductDetails;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ProductStore;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.CancelMallOrderReq;
import com.ydkj.a37e_mall.Classes.Model.Request.GetMallOrderListReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetMallOrderListResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/2/16.
 * 我的订单==》 门店自提
 */

public class StorePickedupFg extends BaseFragment {
    private Activity mActivity;
    private View rootView;
    private MyApplication myApplication;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private PullToRefreshListView plv_wait_pay_order;
    private List<GetMallOrderListResp.ResultEntity.DataEntity> dataEntityList;
    private List<GetMallOrderListResp.ResultEntity.DataEntity> intentList;
    private StorePickedupAdapter storePickedupAdapter;

    private String[] name = {"", "", ""};

    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;//刷新
    private static final int MORE = 2;// 更多
    private int page;
    private String secret;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.comment_good, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        isPrepared = true;
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();

        init();


    }

    private void init() {
        myApplication = MyApplication.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        dataEntityList = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();
        intentList = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();
        plv_wait_pay_order = (PullToRefreshListView) rootView.findViewById(R.id.listview_comment_all);


        storePickedupAdapter = new StorePickedupAdapter(dataEntityList);
        plv_wait_pay_order.setAdapter(storePickedupAdapter);


        plv_wait_pay_order.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetPickedupOrderList(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetPickedupOrderList(MORE);
            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        GetPickedupOrderList(REFRESH);
    }

    //获取门店自提订单列表
    private void GetPickedupOrderList(final int type) {
        // eg:uuid=fcefrgasth1rped9&delivery_type=1&stats=0&page=1&page_size=10
        //  uuid=用户uuid(登录接口返回的uuid)&store_id=当要获取某个门店下的订单时，需要发送非必需参数门店编号，通过api/store/store_list接口获取
        // &delivery_type=订单类型(1为配送上门,2为门店自提)&stats=订单状态id(通过api/store/stats获取)&page=当前页&page_size=每页显示数量的RSA加密字符串
        GetMallOrderListReq req = new GetMallOrderListReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = dataEntityList.size() / 10 + 1;
        }
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setDelivery_type("2");
        req.setStats("0");
        req.setPage(page + "");
        req.setPage_size("10");


        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                mHasLoadedOnce = true;
                Log.e("url", "all_mall_order_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errmsg.equals("暂无订单")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    dataEntityList.clear();
                    plv_wait_pay_order.onRefreshComplete();
                    storePickedupAdapter.notifyDataSetChanged();

                    return;
                }
                if (errno.equals("000")) {
                    plv_wait_pay_order.onRefreshComplete();
                    GetMallOrderListResp resp = GsonImpl.get().toObject(response.toString(), GetMallOrderListResp.class);
                    if (type == LOAD || type == REFRESH) {
                        dataEntityList.clear();
                        dataEntityList.addAll(resp.getResult().getData());
                    } else {
                        dataEntityList.addAll(resp.getResult().getData());
                    }
                    if (dataEntityList.size() % 10 > 0) {
                        plv_wait_pay_order.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        Log.e("url", "123123");
                    } else {
                        plv_wait_pay_order.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    storePickedupAdapter.notifyDataSetChanged();
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 3);
                    Log.e("url", "errmsg==" + errmsg);
                    plv_wait_pay_order.onRefreshComplete();
                } else if (errno.equals("008")) {
//                    CommonUtil.showToast(mActivity, errmsg);
                    dataEntityList.clear();
                    plv_wait_pay_order.onRefreshComplete();
                    storePickedupAdapter.notifyDataSetChanged();
                } else if (errno.equals("0")) {
                    plv_wait_pay_order.onRefreshComplete();
                    Log.e("url", "errmsg==" + errmsg);
                    CommonUtil.showToast(mActivity, "数据加载完了");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //  确认收货
    private void CancelOrder(String id) {
        CustomProgressDialog.createDialog(mActivity).show();
        CancelMallOrderReq req = new CancelMallOrderReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setReturned_delivery("");
        req.setDelivery_no("");
        req.setStats("6");

        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("ssss", "换货订单id==》" + id);

        String url = Const.COMMON_ADDRESS + req.urlString() + id;
        AsyncHttpClient client = new AsyncHttpClient();
        client.put(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "cancel_order_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    GetPickedupOrderList(REFRESH);
                    CommonUtil.showToast(mActivity, errmsg);

                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                    Log.e("url", "errmsg==" + errmsg);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                    GetPickedupOrderList(REFRESH);
                    CustomProgressDialog.Dismiss();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    public class StorePickedupAdapter extends BaseAdapter {
        public List<GetMallOrderListResp.ResultEntity.DataEntity> comment_List;

        public StorePickedupAdapter(List<GetMallOrderListResp.ResultEntity.DataEntity> comment) {
            if (comment == null) {
                comment = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();
            }
            comment_List = comment;
        }

        @Override
        public int getCount() {
            return comment_List.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public GetMallOrderListResp.ResultEntity.DataEntity getItem(int position) {
            return comment_List.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.order_had_complete_listitem, null);
                vh = new ViewHolder();
                vh.lly_all_product_order = (LinearLayout) convertView.findViewById(R.id.lly_all_product_order);
                vh.tv_order_states = (TextView) convertView.findViewById(R.id.tv_order_states);
                vh.tv_order_num = (TextView) convertView.findViewById(R.id.tv_order_num);
                vh.tv_status = (TextView) convertView.findViewById(R.id.tv_status);
                vh.tv_product_num = (TextView) convertView.findViewById(R.id.tv_product_num);
                vh.tv_all_product_price = (TextView) convertView.findViewById(R.id.tv_all_product_price);
                vh.tv_give_integral = (TextView) convertView.findViewById(R.id.tv_give_integral);
                vh.tv_cancel_order = (TextView) convertView.findViewById(R.id.tv_delete_order);
                vh.tv_payment = (TextView) convertView.findViewById(R.id.tv_see_logistics);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            vh.tv_cancel_order.setText("确认收货");
            vh.tv_payment.setText("门店详情");
            vh.tv_status.setText(getItem(position).getStatus());
            vh.tv_order_states.setText("普通订单");
            vh.tv_order_num.setText(getItem(position).getSn());
            DecimalFormat df = new DecimalFormat("0.00");
            vh.tv_all_product_price.setText("¥ " + df.format(Float.parseFloat(dataEntityList.get(position).getTotal_fee())));//保留两位小数
            vh.tv_product_num.setText("共计" + getItem(position).getNum() + "件商品");


            vh.lly_all_product_order.removeAllViews();
            LinearLayout productLayout = (LinearLayout) LayoutInflater.from(mActivity).inflate(R.layout.mall_order_layout, null);
            ImageView img_thumb = (ImageView) productLayout.findViewById(R.id.img_thumb);
            TextView tv_describe = (TextView) productLayout.findViewById(R.id.tv_describe);
            TextView tv_price = (TextView) productLayout.findViewById(R.id.tv_price);
            TextView tv_postage = (TextView) productLayout.findViewById(R.id.tv_postage);
            TextView tv_type_content = (TextView) productLayout.findViewById(R.id.tv_type_content);
            TextView tv_num = (TextView) productLayout.findViewById(R.id.tv_num);
            tv_describe.setText(getItem(position).getInfo());
            tv_price.setText(getItem(position).getTotal_fee());
            for (int i = 0; i < getItem(position).getProduct().size(); i++) {
                if (i == 0) {
                    tv_type_content.setText(getItem(position).getProduct().get(i).getStandard_type() + ":"
                            + getItem(position).getProduct().get(i).getStandard_name());
                } else {
                    tv_type_content.setText(tv_type_content.getText().toString() + "\n" + getItem(position).getProduct().get(i).getStandard_type() + ":"
                            + getItem(position).getProduct().get(i).getStandard_name());
                }
            }
            tv_num.setText("X" + getItem(position).getNum());
            ImageLoader.getInstance().displayImage(getItem(position).getThumb(), img_thumb, displayImageOptions);


            vh.lly_all_product_order.addView(productLayout);


            //门店详情
            final ViewHolder finalVh = vh;
            vh.tv_payment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, ProductStore.class);
                    intent.putExtra("url", getItem(position).getUrl());
                    startActivity(intent);
                }
            });


            //确认收货
            vh.tv_cancel_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CancelOrder(getItem(position).getId());
                }
            });


            //商品详细
            productLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, ProductDetails.class);
                    intent.putExtra("id", getItem(position).getProduct_id());
                    startActivity(intent);
                }
            });

            return convertView;
        }

        public class ViewHolder {
            private LinearLayout lly_all_product_order;
            private TextView tv_order_states, tv_order_num, tv_status, tv_product_num, tv_all_product_price, tv_give_integral;
            private TextView tv_cancel_order, tv_payment;
        }
    }

}
